﻿
import sys
import argparse

from PySide.QtCore import QObject
from PySide.QtGui import QMenu
from PySide.QtGui import QAction

from karmadbg.uicore.uicmd import registerUiCommand
from karmadbg.dbgcore.util import showtraceback


class MenuException(Exception):
    pass

class MainMenuManager(QObject):
    
    def __init__(self, mainMenuSettings, uimanager):
        QObject.__init__(self)
        self.menuBar = uimanager.mainwnd.menuBar()
        self.uimanager = uimanager
        self.settings = mainMenuSettings
        self.argparser = None
        self.buildMenu()

        registerUiCommand("mainmenu", "managed main menu", self.onMainMenuCommand)

    def buildMenu(self):
        self.menuBar.clear()
        for menuSettings in self.settings.menuItems:
            self.addMenuGroup(self.menuBar,menuSettings)

    def addMenuGroup(self, parent, menuSettings):
        menu = QMenu(menuSettings.displayName)
        parent.addMenu(menu)
        for menuItem in menuSettings.menuItems:
            if menuItem.separator:
                menu.addSeparator()
            elif len(menuItem.menuItems) > 0:
                self.addMenuGroup(menu, menuItem)
            elif menuItem.toggleWidget:
                widget = self.uimanager.getWidget(menuItem.toggleWidget)
                menu.addAction(widget.toggleViewAction())
            elif menuItem.actionName:
                menu.addAction( self.uimanager.actions[menuItem.actionName] )
            else:
                menu.addMenu(menuItem.displayName)

    def onMainMenuCommand(self, *args):

        try:
            self.makeArgParser()
            commandArgs = self.argparser.parse_args(args)
            if commandArgs : commandArgs.func(commandArgs)
        except MenuException as menuException:
            print menuException.message

    def getParentSettings(self, parentMenu):

        groupSettings = self.settings

        if not parentMenu:
            return groupSettings

        for group in parentMenu.split('.'):
            for menuItem in groupSettings.menuItems:
                name = menuItem.displayName if menuItem.name == "" else menuItem.name
                if name == group:
                    groupSettings = menuItem
                    break
            else:
                raise MenuException("not found menu group")

        return groupSettings


    def registerToggleWidgetMenu(self, widgetName, parentMenu):
        pass

    def registerGroupMenu(self, groupName, parentMenu):
        parentSettings = self.getParentSettings(parentMenu)
        itemSettings = parentSettings.addItem(groupName)
        self.uimanager.saveSettings()
        self.buildMenu()

    def makeArgParser(self):

        if self.argparser: return self.argparser

        class ArgParser(argparse.ArgumentParser):

            def error(self, message):
                sys.stdout.write('error: %s\n' % message)
                self.print_help()
                self.exit()

            def parse_args(self, *args):
                try:
                   return super(ArgParser, self).parse_args(*args)
                except SystemExit:
                    return None
             
        self.argparser = ArgParser(prog=".mainmenu")

        subparser = self.argparser.add_subparsers(help='sub-command help')
     
        addparser = subparser.add_parser('add')
        addparser.add_argument('--type', type=str, choices=['group'], help ="type of menu item")
        addparser.add_argument('--parent', type=str, help ="parent item")
        addparser.set_defaults(func=self.addMenuItemCommand)

        removeparser = subparser.add_parser('remove')

        listparser = subparser.add_parser('list')
        listparser.add_argument('parentItem', type=str, nargs='?', help ="parent item", default="")
        listparser.set_defaults(func=self.listMenuItemCommand)

        return self.argparser

    def addMenuItemCommand(self, args):
        print args

    def listMenuItemCommand(self, args):
        parentSettings = self.getParentSettings(args.parentItem)
        for itemSettings in parentSettings.menuItems:
            if itemSettings.separator:
                print "-" * 10
            elif len(itemSettings.menuItems) > 0:
                print self.getPrintableName(itemSettings), "->"
            elif itemSettings.toggleWidget:
                widget = self.uimanager.getWidget(itemSettings.toggleWidget)
                print widget.windowTitle(), "V"
            elif itemSettings.actionName:
                print self.uimanager.actions[itemSettings.actionName].text()
            else:
                print self.getPrintableName(itemSettings)

    def getPrintableName(self, itemSettings):
        if itemSettings.name:
            return itemSettings.name
        elif itemSettings.displayName:
            return itemSettings.displayName
        else:
            return "[NoName]"




    



